<template>
  <div class="order-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待付款" value="pending_payment" />
            <el-option label="待发货" value="pending_shipment" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="收货人">
          <el-input v-model="searchForm.receiverName" placeholder="请输入收货人姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.receiverPhone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleExport">导出订单</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-operations">
            <el-button-group>
              <el-button type="primary" @click="handleBatchShip">批量发货</el-button>
              <el-button type="success" @click="handleBatchPrint">批量打印</el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column label="商品信息" min-width="300">
          <template #default="{ row }">
            <div v-for="item in row.items" :key="item.id" class="order-item">
              <el-image
                :src="item.image"
                :preview-src-list="[item.image]"
                fit="cover"
                class="item-image"
              />
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-specs">
                  <el-tag
                    v-for="(spec, index) in item.specs"
                    :key="index"
                    size="small"
                    class="spec-tag"
                  >
                    {{ spec.name }}: {{ spec.value }}
                  </el-tag>
                </div>
                <div class="item-price-qty">
                  <span class="price">¥{{ item.price.toFixed(2) }}</span>
                  <span class="qty">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货信息" width="200">
          <template #default="{ row }">
            <div class="receiver-info">
              <div>{{ row.receiverName }} {{ row.receiverPhone }}</div>
              <div class="address">{{ row.receiverAddress }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            <div class="amount">
              <div class="total">¥{{ row.totalAmount.toFixed(2) }}</div>
              <div class="freight" v-if="row.freight > 0">含运费 ¥{{ row.freight.toFixed(2) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button
              v-if="row.status === 'pending_shipment'"
              type="success"
              link
              @click="handleShip(row)"
            >
              发货
            </el-button>
            <el-button
              v-if="row.status === 'shipped'"
              type="primary"
              link
              @click="handleLogistics(row)"
            >
              物流
            </el-button>
            <el-button
              v-if="['pending_payment', 'pending_shipment'].includes(row.status)"
              type="danger"
              link
              @click="handleCancel(row)"
            >
              取消
            </el-button>
            <el-button
              v-if="['shipped', 'completed'].includes(row.status)"
              type="warning"
              link
              @click="handleRefund(row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialog.visible"
      :title="shipDialog.isBatch ? '批量发货' : '订单发货'"
      width="600px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipDialog.form"
        :rules="shipDialog.rules"
        label-width="100px"
      >
        <template v-if="!shipDialog.isBatch">
          <el-form-item label="订单编号">
            <span>{{ shipDialog.order?.orderNo }}</span>
          </el-form-item>
          <el-form-item label="收货信息">
            <div class="receiver-info">
              <div>{{ shipDialog.order?.receiverName }} {{ shipDialog.order?.receiverPhone }}</div>
              <div class="address">{{ shipDialog.order?.receiverAddress }}</div>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipDialog.form.company" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
            <el-option label="京东物流" value="JD" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipDialog.form.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="发货备注" prop="remark">
          <el-input
            v-model="shipDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入发货备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="shipDialog.loading" @click="submitShip">
          确认发货
        </el-button>
      </template>
    </el-dialog>

    <!-- 物流信息对话框 -->
    <el-dialog v-model="logisticsDialog.visible" title="物流信息" width="800px">
      <div v-loading="logisticsDialog.loading">
        <div class="logistics-info">
          <div class="info-item">
            <span class="label">物流公司：</span>
            <span class="value">{{ logisticsDialog.info.company }}</span>
          </div>
          <div class="info-item">
            <span class="label">物流单号：</span>
            <span class="value">{{ logisticsDialog.info.trackingNo }}</span>
            <el-button type="primary" link @click="copyTrackingNo">
              复制单号
            </el-button>
          </div>
        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in logisticsDialog.info.traces"
            :key="index"
            :timestamp="activity.time"
            :type="index === 0 ? 'primary' : ''"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog
      v-model="refundDialog.visible"
      title="订单退款"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundDialog.form"
        :rules="refundDialog.rules"
        label-width="100px"
      >
        <el-form-item label="订单编号">
          <span>{{ refundDialog.order?.orderNo }}</span>
        </el-form-item>
        <el-form-item label="订单金额">
          <span class="amount">¥{{ refundDialog.order?.totalAmount.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="退款金额" prop="amount">
          <el-input-number
            v-model="refundDialog.form.amount"
            :min="0"
            :max="refundDialog.order?.totalAmount"
            :precision="2"
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-select v-model="refundDialog.form.reason" placeholder="请选择退款原因">
            <el-option label="商品质量问题" value="quality" />
            <el-option label="商品与描述不符" value="description" />
            <el-option label="商品损坏" value="damaged" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款说明" prop="remark">
          <el-input
            v-model="refundDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入退款说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="refundDialog.loading" @click="submitRefund">
          确认退款
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMerchantOrderList,
  getMerchantOrderDetail,
  updateMerchantOrderStatus,
  shipMerchantOrder,
  batchShipMerchantOrder,
  getMerchantOrderLogistics,
  refundMerchantOrder,
  exportMerchantOrder
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  dateRange: [],
  receiverName: '',
  receiverPhone: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 选中的行
const selectedRows = ref([])

// 发货相关
const shipDialog = reactive({
  visible: false,
  loading: false,
  isBatch: false,
  order: null,
  form: {
    company: '',
    trackingNo: '',
    remark: ''
  },
  rules: {
    company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
    trackingNo: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
  }
})

// 物流相关
const logisticsDialog = reactive({
  visible: false,
  loading: false,
  info: {
    company: '',
    trackingNo: '',
    traces: []
  }
})

// 退款相关
const refundDialog = reactive({
  visible: false,
  loading: false,
  order: null,
  form: {
    amount: 0,
    reason: '',
    remark: ''
  },
  rules: {
    amount: [{ required: true, message: '请输入退款金额', trigger: 'blur' }],
    reason: [{ required: true, message: '请选择退款原因', trigger: 'change' }]
  }
})

// 物流公司列表
const logisticsCompanies = [
  { code: 'SF', name: '顺丰速运' },
  { code: 'YTO', name: '圆通速递' },
  { code: 'ZTO', name: '中通快递' },
  { code: 'STO', name: '申通快递' },
  { code: 'YD', name: '韵达快递' },
  { code: 'EMS', name: 'EMS' }
]

// 表单验证规则
const shipRules = {
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

const refundRules = {
  amount: [
    { required: true, message: '请输入退款金额', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请选择退款原因', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入详细说明', trigger: 'blur' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending_payment: 'warning',
    pending_shipment: 'primary',
    shipped: 'success',
    completed: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending_payment: '待付款',
    pending_shipment: '待发货',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return statusMap[status] || '未知'
}

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderList({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    })
    tableData.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 处理选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 订单详情
const handleDetail = (row) => {
  // TODO: 实现订单详情页面跳转
}

// 发货
const handleShip = (row) => {
  shipDialog.isBatch = false
  shipDialog.order = row
  shipDialog.form = {
    company: '',
    trackingNo: '',
    remark: ''
  }
  shipDialog.visible = true
}

// 批量发货
const handleBatchShip = () => {
  const pendingShipmentOrders = selectedRows.value.filter(
    row => row.status === 'pending_shipment'
  )
  if (pendingShipmentOrders.length === 0) {
    ElMessage.warning('请选择待发货的订单')
    return
  }
  shipDialog.isBatch = true
  shipDialog.order = null
  shipDialog.form = {
    company: '',
    trackingNo: '',
    remark: ''
  }
  shipDialog.visible = true
}

// 提交发货
const submitShip = async () => {
  if (!shipFormRef.value) return
  await shipFormRef.value.validate(async (valid) => {
    if (valid) {
      shipDialog.loading = true
      try {
        if (shipDialog.isBatch) {
          const orderIds = selectedRows.value
            .filter(row => row.status === 'pending_shipment')
            .map(row => row.id)
          await batchShipMerchantOrder({
            orderIds,
            ...shipDialog.form
          })
        } else {
          await shipMerchantOrder(shipDialog.order.id, shipDialog.form)
        }
        ElMessage.success('发货成功')
        shipDialog.visible = false
        getList()
      } catch (error) {
        ElMessage.error('发货失败')
      } finally {
        shipDialog.loading = false
      }
    }
  })
}

// 物流信息
const handleLogistics = async (row) => {
  logisticsDialog.visible = true
  logisticsDialog.loading = true
  try {
    const { data } = await getMerchantOrderLogistics(row.id)
    logisticsDialog.info = data
  } catch (error) {
    ElMessage.error('获取物流信息失败')
  } finally {
    logisticsDialog.loading = false
  }
}

// 复制物流单号
const copyTrackingNo = () => {
  navigator.clipboard.writeText(logisticsDialog.info.trackingNo).then(() => {
    ElMessage.success('复制成功')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm('确认取消该订单吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await updateMerchantOrderStatus(row.id, 'cancelled')
      ElMessage.success('取消成功')
      getList()
    } catch (error) {
      ElMessage.error('取消失败')
    }
  })
}

// 退款
const handleRefund = (row) => {
  refundDialog.order = row
  refundDialog.form = {
    amount: row.totalAmount,
    reason: '',
    remark: ''
  }
  refundDialog.visible = true
}

// 提交退款
const submitRefund = async () => {
  if (!refundFormRef.value) return
  await refundFormRef.value.validate(async (valid) => {
    if (valid) {
      refundDialog.loading = true
      try {
        await refundMerchantOrder(refundDialog.order.id, refundDialog.form)
        ElMessage.success('退款成功')
        refundDialog.visible = false
        getList()
      } catch (error) {
        ElMessage.error('退款失败')
      } finally {
        refundDialog.loading = false
      }
    }
  })
}

// 批量打印
const handleBatchPrint = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要打印的订单')
    return
  }
  // TODO: 实现批量打印功能
}

// 导出订单
const handleExport = async () => {
  try {
    const response = await exportMerchantOrder({
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    })
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `订单列表_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.order-list {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-operations {
        display: flex;
        gap: 10px;
      }
    }
  }

  .order-item {
    display: flex;
    gap: 10px;
    padding: 10px 0;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
    }

    .item-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }

    .item-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 5px;

      .item-name {
        font-size: 14px;
        color: #303133;
      }

      .item-specs {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;

        .spec-tag {
          margin-right: 5px;
        }
      }

      .item-price-qty {
        display: flex;
        justify-content: space-between;
        color: #909399;
        font-size: 13px;

        .price {
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
  }

  .receiver-info {
    font-size: 13px;
    color: #606266;

    .address {
      margin-top: 5px;
      color: #909399;
    }
  }

  .amount {
    .total {
      color: #f56c6c;
      font-weight: bold;
    }

    .freight {
      font-size: 12px;
      color: #909399;
      margin-top: 5px;
    }
  }

  .logistics-info {
    .logistics-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;

      .company,
      .tracking-no {
        margin-bottom: 10px;

        .label {
          color: #909399;
          margin-right: 10px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 